const PizZip = require("pizzip");
const Docxtemplater = require("docxtemplater");
const axios = require("axios");
exports.main = async (event, context) => {
	// 读取模板文件
	try {
		// 使用 axios 从远程 URL 下载文件，并指定响应类型为 arraybuffer
		const content = await axios({
			method: "get",
			url: event.url,
			responseType: "arraybuffer",
		});
		console.log(content , 'content');

		const zip = new PizZip(content.data);
		console.log(zip , 'zip');

		// 创建 Docxtemplater 实例
		const doc = new Docxtemplater(zip, {
			parser: require("docxtemplater/expressions"), // 确保表达式解析器被正确导入
			linebreaks: true,
			paragraphLoop: true, 
			
		});
		console.log(doc , 'doc');

		// 渲染模板
		await doc.renderAsync(event.data);

		// 生成 Word 文件 
		const buffer = doc.getZip().generate({
			type: "nodebuffer",
			mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
		});
		console.log(buffer , 'buffer');
		
		let res = await uniCloud.uploadFile({
			cloudPath: "模板生成文件.docx",
			fileContent: buffer
		})
		console.log(res , 'res');

		// 保存文件
		return {
			code: 200,
			data: res.fileID
		}
	} catch (error) { 
		console.log(error, 'error');
		return {
			code: 500,
			data: {},
			message: error
		}
	}
	//返回数据给客户端
};